import 'dart:io';

import 'package:excel_utils/extend/string_extend.dart';
import 'package:excel_utils/pages/daily/daily_data_entry/daily_data_entry_page.dart';
import 'package:excel_utils/pages/view/calendar_view.dart';
import 'package:excel_utils/repository/daily_entry/daily_entry_repository.dart';
import 'package:excel_utils/repository/k8/k8_repository.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:url_launcher/url_launcher.dart';

import 'bean/CmcTicketBean.dart';
import 'bean/DailyInformationBean.dart';
import 'bean/DailyVoteBean.dart';
import 'bean/IndependentStatisticalBean.dart';
import 'bean/LocalDeliveryStatisticsBean.dart';
import 'bean/OtherTopThirtyBean.dart';
import 'bean/ThirdPartyBean.dart';
import 'bloc/daily_report_bloc.dart';

class DailyReportPage extends StatefulWidget {
  const DailyReportPage({super.key});

  @override
  State<DailyReportPage> createState() => _DailyReportPageState();
}

class _DailyReportPageState extends State<DailyReportPage> {
  DailyReportBloc? dailyReportBloc;
  ScrollController controller = ScrollController(keepScrollOffset: true);
  File? file;
  String loginAccount = "";
  String loginPassword = "";

  int year = 0000;
  int month = 00;
  int day = 00;
  int hour = 00;
  int minute = 00;
  int second = 00;
  // 运单列印  waybillPrinting
  String waybillPrintingStart = "";
  String waybillPrintingEnd = "";
  bool waybillPrintingLoading = false;
  DailyInformationBean? waybillPrintingBean;
  DailyInformationBean? dailyInformationAllBean;

  String localDeliveryStatisticsStart = "";
  String localDeliveryStatisticsEnd = "";
  bool localDeliveryStatisticsLoading = false;
  LocalDeliveryStatisticsBean? localDeliveryStatisticsBean;
  IndependentStatisticalBean? independentStatisticalBean;

  String topThirtyStart = "";
  String topThirtyEnd = "";
  bool otherTopThirtyLoading = false;
  OtherTopThirtyBean? otherTopThirtyBean;

  String thirdPartyStart = "";
  String thirdPartyEnd = "";
  bool thirdPartyLoading = false;
  ThirdPartyBean? thirdPartyBean;

  String cmsTicketStart = "";
  String cmsTicketEnd = "";
  bool cmsTicketLoading = false;
  CmsTicketBean? cmsTicketBean;

  // 指定客户编号查询数据
  List<String> customerNo = ["9821229", "9821190"];
  // specifyCustomerNo
  String specifyCustomerStart = "";
  String specifyCustomerEnd = "";
  bool specifyCustomerLoading = false;
  bool? specifyCustomerCurrentMonth = false;

  String dailyVoteStart = "";
  String dailyVoteEnd = "";
  bool dailyVoteLoading = false;
  DailyVoteBean? dailyVoteBean;

  String signStatisticsStart = "";
  String signStatisticsEnd = "";
  bool signStatisticsLoading = false;
  List<Map<String, dynamic>> signStatistics = [];

  @override
  void initState() {
    DateTime now = DateTime.now();
    if (now.day == 1) {
      now = now.subtract(const Duration(days: 1));
    }
    year = now.year;
    month = now.month;
    day = now.day;
    hour = now.hour;
    minute = now.minute;
    second = now.second;
    if (now.weekday == 5 && hour >= 20) {
      day += 1;
    }
    int tempDay = day;
    if (DateTime.now().day > 1) {
      tempDay = day - 1;
    }
    waybillPrintingStart = "${year}-${month.toString().padLeft(2, '0')}-${(tempDay).toString().padLeft(2, '0')} 00:00:00";
    waybillPrintingEnd = "${year}-${month.toString().padLeft(2, '0')}-${(tempDay).toString().padLeft(2, '0')} 23:59:59";
    // localDeliveryStatisticsStart = "${year}-${month.toString().padLeft(2, '0')}-${(day - 1).toString().padLeft(2, '0')} 00:00:00";
    localDeliveryStatisticsStart = "${year}-${month.toString().padLeft(2, '0')}-01 00:00:00";
    localDeliveryStatisticsEnd = "${year}-${month.toString().padLeft(2, '0')}-${(tempDay).toString().padLeft(2, '0')} 23:59:59";
    // 首30 查看1号到昨天的数据
    topThirtyStart = "${year}-${month.toString().padLeft(2, '0')}-01 00:00:00";
    topThirtyEnd = "${year}-${month.toString().padLeft(2, '0')}-${(tempDay).toString().padLeft(2, '0')} 23:59:59";
    // CMS 数据 查询当月全部数据
    cmsTicketStart = "${year}-${month.toString().padLeft(2, '0')}-${(1).toString().padLeft(2, '0')} 00:00:00";
    cmsTicketEnd = "${year}-${month.toString().padLeft(2, '0')}-${(tempDay).toString().padLeft(2, '0')} 23:59:59";
    // 查询指定客户数据日期范围
    specifyCustomerStart = "${year}-${month.toString().padLeft(2, '0')}-${(1).toString().padLeft(2, '0')} 00:00:00";
    specifyCustomerEnd = "${year}-${month.toString().padLeft(2, '0')}-${(tempDay).toString().padLeft(2, '0')} 23:59:59";

    signStatisticsStart = "${year}-${month.toString().padLeft(2, '0')}-${(tempDay).toString().padLeft(2, '0')} 00:00:00";
    signStatisticsEnd = "${year}-${month.toString().padLeft(2, '0')}-${(tempDay).toString().padLeft(2, '0')} 23:59:59";
    // 第三方数据
    thirdPartyStart = "${year}-${month.toString().padLeft(2, '0')}-${(tempDay).toString().padLeft(2, '0')} 00:00:00";
    thirdPartyEnd = "${year}-${month.toString().padLeft(2, '0')}-${(tempDay).toString().padLeft(2, '0')} 23:59:59";
    // 每天票數統計
    dailyVoteStart = "${year}-${month.toString().padLeft(2, '0')}-${(1).toString().padLeft(2, '0')} 00:00:00";
    dailyVoteEnd = "${year}-${month.toString().padLeft(2, '0')}-${(tempDay).toString().padLeft(2, '0')} 23:59:59";
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (BuildContext context) => DailyReportBloc(context.read<K8Repository>(), context.read<DailyEntryRepository>()),
      child: BlocBuilder<DailyReportBloc, DailyReportState>(
        builder: (BuildContext context, DailyReportState state) {
          dailyReportBloc = dailyReportBloc ?? context.read<DailyReportBloc>();
          if (state is DailyReportLocalDeliveryStatisticsLoadingState) {
            localDeliveryStatisticsLoading = true;
            localDeliveryStatisticsBean = null;
            independentStatisticalBean = null;
          } else if (state is DailyReportLocalDeliveryStatisticsSuccessState) {
            localDeliveryStatisticsLoading = false;
            localDeliveryStatisticsBean = state.localDeliveryStatisticsBean;
            independentStatisticalBean = state.independentStatisticalBean;
          } else if (state is DailyReportLocalDeliveryStatisticsFailureState) {
            localDeliveryStatisticsLoading = false;
          } else if (state is OtherTopThirtyLoadingState) {
            otherTopThirtyLoading = true;
            otherTopThirtyBean = null;
          } else if (state is OtherTopThirtySuccessState) {
            otherTopThirtyLoading = false;
            otherTopThirtyBean = state.otherTopThirtyBean;
          } else if (state is OtherTopThirtyFailureState) {
            otherTopThirtyLoading = false;
          } else if (state is ThirdPartyLoadingState) {
            thirdPartyLoading = true;
            thirdPartyBean = null;
          } else if (state is ThirdPartySuccessState) {
            thirdPartyLoading = false;
            thirdPartyBean = state.thirdPartyBean;
          } else if (state is ThirdPartyFailureState) {
            thirdPartyLoading = false;
          } else if (state is CmsTicketLoadingState) {
            cmsTicketLoading = true;
            cmsTicketBean = null;
          } else if (state is CmsTicketSuccessState) {
            cmsTicketLoading = false;
            cmsTicketBean = state.cmsTicketBean;
          } else if (state is CmsTicketFailureState) {
            cmsTicketLoading = false;
          } else if (state is DailyVoteLoadingState) {
            dailyVoteLoading = true;
            dailyVoteBean = null;
          } else if (state is DailyVoteSuccessState) {
            dailyVoteLoading = false;
            dailyVoteBean = state.dailyVoteBean;
          } else if (state is DailyVoteFailureState) {
            dailyVoteLoading = false;
          } else if (state is DailyInformationLoadingState) {
            waybillPrintingLoading = true;
            waybillPrintingBean = null;
          } else if (state is DailyInformationSuccessState) {
            waybillPrintingLoading = false;
            waybillPrintingBean = state.dailyInformationBean;
            dailyInformationAllBean = state.dailyInformationAllBean;
          } else if (state is DailyInformationFailureState) {
            waybillPrintingLoading = false;
          } else if (state is SignStatisticsLoadingState) {
            signStatisticsLoading = true;
            signStatistics.clear();
          } else if (state is SignStatisticsSuccessState) {
            signStatisticsLoading = false;
            signStatistics = state.signStatistics;
          } else if (state is SignStatisticsFailureState) {
            signStatisticsLoading = false;
          }
          return buildUI(context);
        },
      ),
    );
  }

  Widget buildUI(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        controller: controller,
        child: Padding(
          padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
          child: Column(
            children: [
              Row(
                children: [
                  const Text("每日报表"),
                  ElevatedButton(
                      onPressed: () async {
                        var startDate15Time = DateTime.parse(signStatisticsStart).subtract(Duration(days: 14));
                        String startDate15 =
                            "${startDate15Time.year}-${startDate15Time.month.toString().padLeft(2, '0')}-${(startDate15Time.day).toString().padLeft(2, '0')} 00:00:00";
                        dailyReportBloc?.add(SignStatisticsEvent(startDate: signStatisticsStart, endDate: signStatisticsEnd, startDate15: startDate15));
                        dailyReportBloc?.add(CmsTicketDataEvent(startDate: cmsTicketStart, endDate: cmsTicketEnd));
                        dailyReportBloc
                            ?.add(DailyReportLocalDeliveryStatisticsDataEvent(startDate: localDeliveryStatisticsStart, endDate: localDeliveryStatisticsEnd));
                        dailyReportBloc?.add(DailyInformationEvent(startDate: waybillPrintingStart, endDate: waybillPrintingEnd, custType: '套票客'));
                        dailyReportBloc?.add(DailyVoteDataEvent(startDate: dailyVoteStart, endDate: dailyVoteEnd));
                        dailyReportBloc?.add(OtherTopThirtyDataEvent(startDate: topThirtyStart, endDate: topThirtyEnd));
                        dailyReportBloc?.add(ThirdPartyDataEvent(startDate: thirdPartyStart, endDate: thirdPartyEnd));
                      },
                      child: Text("一键查询")),
                  Row(
                    children: [
                      Checkbox(value: false, onChanged: (value) {}),
                      const Text("是否携带label"),
                    ],
                  ),
                  const Spacer(),
                  // 选择文件
                  TextButton(
                      onPressed: () async {
                        var filePickerResult = await FilePicker.platform.pickFiles(allowedExtensions: ['xlsx'], type: FileType.custom, allowMultiple: true);
                        if (filePickerResult != null) {
                          file = File(filePickerResult.files.single.xFile.path.toString());
                          setState(() {});
                        }
                      },
                      child: const Text("选择文件")),
                  const Spacer(),
                  Text("${file?.path}"),
                ],
              ),
              _waybillPrintingWidget(context), // 运单列印
              const Divider(color: Colors.indigoAccent),
              _cmsTicketWidget(context), // CMS 票數表
              const Divider(color: Colors.orange),
              // // 指定客户查询
              // _specifyCustomerWidget(context),
              // const Divider(color: Colors.green),
              _signStatisticsWidget(context), // 查询签收统计
              // 派送品質統計表
              const Divider(color: Colors.yellow),
              // 同城本地簽收統計
              _localDeliveryStatisticsWidget(context),
              const Divider(color: Colors.deepPurple),
              // 每天票數統計
              _dailyVoteWidget(context),
              const Divider(color: Colors.red),
              // 首三十
              _topThirtyWidget(context),
              const Divider(color: Colors.pink),
              // 第三方
              _thirdPartyWidget(context),
              const Divider(color: Colors.pink),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {},
        child: const BackButton(),
      ),
    );
  }

  // 运单列印
  Widget _waybillPrintingWidget(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(
              width: 200,
              child: IconButton(
                onPressed: () {
                  if (waybillPrintingLoading) return;
                  dailyReportBloc?.add(DailyInformationEvent(startDate: waybillPrintingStart, endDate: waybillPrintingEnd, custType: '套票客'));
                },
                icon: AnimatedSwitcher(
                    duration: const Duration(seconds: 1),
                    child: waybillPrintingLoading
                        ? const SizedBox(key: ValueKey("loading"), width: 40, height: 40, child: CircularProgressIndicator())
                        : const SizedBox(
                            key: ValueKey("search"),
                            height: 40,
                            child: Row(children: [Icon(Icons.search, color: Colors.green), Text("查询运单列印", style: TextStyle(color: Colors.green))]))),
              ),
            ),
            CalendarView(
              day: 1,
              onInitDateChanged: (startDateTime, startStr, endDateTime, endStr) {
                waybillPrintingStart = "${startStr}";
                waybillPrintingEnd = "${endStr}";
              },
              onDateStartChanged: (startDateTime, startStr) {
                print("disMonthFeeStartDate: $startDateTime, $startStr");
                waybillPrintingStart = "${startStr}";
              },
              onDateEndChanged: (endDateTime, endStr) {
                print("disMonthFeeEndDate: $endDateTime, $endStr");
                waybillPrintingEnd = "${endStr}";
              },
            ),
          ],
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (waybillPrintingBean != null && waybillPrintingBean?.status == 1) ...[
              _dateWidget(startTime: '$waybillPrintingStart', endTime: '$waybillPrintingEnd', dataCount: waybillPrintingBean!.data!.length),
              Row(
                children: [
                  TextButton(
                      onPressed: () {
                        StringBuffer sb = StringBuffer();
                        String tempStr = waybillPrintingBean!.data
                                ?.map((e) =>
                                    "${e.bLAPPLYDATE}\t${e.cMCODE}\t${e.bLCOST}\t${e.bLBILLNUM}\t${e.bLPCOST}\t${e.bGNAME}\t${e.bLVALIDITY}\t${e.cMNAME}\t${e.cMADDRESS}")
                                .join("\n")
                                .toString() ??
                            "";
                        sb.write(tempStr);
                        sb.toString().copyValue();
                      },
                      child: Text("C运单列印")),
                  TextButton(
                      onPressed: () async {
                        _copyAllData();
                      },
                      child: Text("CAll运单列印")),
                ],
              ),
              Table(
                border: TableBorder.all(color: Colors.black),
                children: [
                  tabRows(["日期", "客户编号", "套票费用", "数量", "套票单价", "群组名称", "有效期", "客户名称", "注册地址"]),
                  ...waybillPrintingBean!.data!.map((e) {
                    const testStyle14 = TextStyle(fontSize: 14);
                    return TableRow(children: [
                      TableCell(child: Text(e.bLAPPLYDATE.toString(), style: testStyle14)),
                      TableCell(child: Text(e.cMCODE.toString(), style: testStyle14)),
                      TableCell(child: Text(e.bLCOST.toString(), style: testStyle14)),
                      TableCell(child: Text(e.bLBILLNUM.toString(), style: testStyle14)),
                      TableCell(child: Text(e.bLPCOST.toString(), style: testStyle14)),
                      TableCell(child: Text(e.bGNAME.toString(), style: testStyle14)),
                      TableCell(child: Text(e.bLVALIDITY.toString(), style: testStyle14)),
                      TableCell(child: Text(e.cMNAME.toString(), maxLines: 1, style: testStyle14)),
                      TableCell(child: Text(e.cMADDRESS.toString(), maxLines: 1, style: testStyle14)),
                    ]);
                  }),
                ],
              ),
              Container(
                padding: EdgeInsets.all(10),
                child: Column(
                  children: [
                    Table(
                      border: TableBorder.all(color: Colors.black),
                      children: [
                        TableRow(children: [
                          const TableCell(child: Text("当前总数据")),
                          TableCell(child: Text("${waybillPrintingBean!.data!.fold(0, (value, element) => value + element.bLCOST! ?? 0)}")),
                          TableCell(child: Text("${waybillPrintingBean!.data!.fold(0, (value, element) => value + element.bLBILLNUM! ?? 0)}")),
                          const TableCell(child: Text("")),
                          const TableCell(child: Text("")),
                        ]),
                        const TableRow(children: [
                          TableCell(child: Text("")),
                          TableCell(child: Text("费用")),
                          TableCell(child: Text("数量")),
                          TableCell(child: Text("平均價/票")),
                          TableCell(child: Text("")),
                        ]),
                        TableRow(children: [
                          const TableCell(child: Text("当月总数据")),
                          TableCell(child: Text("${dailyInformationAllBean!.data!.fold(0, (value, element) => value + element.bLCOST! ?? 0)}")),
                          TableCell(child: Text("${dailyInformationAllBean!.data!.fold(0, (value, element) => value + element.bLBILLNUM! ?? 0)}")),
                          TableCell(
                              child: Text(
                                  "${(dailyInformationAllBean!.data!.fold(0, (value, element) => value + element.bLCOST! ?? 0) / dailyInformationAllBean!.data!.fold(0, (value, element) => value + element.bLBILLNUM! ?? 0)).toStringAsFixed(1).toString()}")),
                          const TableCell(child: Text("")),
                        ]),
                        TableRow(children: [
                          const TableCell(child: Text("CXC直客")),
                          TableCell(
                              child: Text("${dailyInformationAllBean!.data!.fold(0, (value, element) {
                            if (element.bGNAME.toString().contains("CXC")) {
                              return value + element.bLCOST!;
                            } else {
                              return value;
                            }
                          })}")),
                          TableCell(
                              child: Text("${dailyInformationAllBean!.data!.fold(0, (value, element) {
                            if (element.bGNAME.toString().contains("CXC")) {
                              return value + element.bLBILLNUM!;
                            } else {
                              return value;
                            }
                          })}")),
                          TableCell(
                              child: Text((dailyInformationAllBean!.data!.fold(0, (value, element) {
                                        if (element.bGNAME.toString().contains("CXC")) {
                                          return value + element.bLCOST!;
                                        } else {
                                          return value;
                                        }
                                      }) /
                                      dailyInformationAllBean!.data!.fold(0, (value, element) {
                                        if (element.bGNAME.toString().contains("CXC")) {
                                          return value + element.bLBILLNUM!;
                                        } else {
                                          return value;
                                        }
                                      }))
                                  .toStringAsFixed(1)
                                  .toString())),
                          TableCell(
                              child: Text("${(dailyInformationAllBean!.data!.fold(0, (value, element) {
                                    if (element.bGNAME.toString().contains("CXC")) {
                                      return value + element.bLCOST!;
                                    } else {
                                      return value;
                                    }
                                  }) / dailyInformationAllBean!.data!.fold(0, (value, element) => value + element.bLCOST! ?? 0) * 100).toStringAsFixed(1).toString()}%")),
                        ]),
                        TableRow(children: [
                          const TableCell(child: Text("加盟商")),
                          TableCell(
                              child: Text("${dailyInformationAllBean!.data!.fold(0, (value, element) {
                            if (!element.bGNAME.toString().contains("CXC")) {
                              return value + element.bLCOST!;
                            } else {
                              return value;
                            }
                          })}")),
                          TableCell(
                              child: Text("${dailyInformationAllBean!.data!.fold(0, (value, element) {
                            if (!element.bGNAME.toString().contains("CXC")) {
                              return value + element.bLBILLNUM!;
                            } else {
                              return value;
                            }
                          })}")),
                          TableCell(
                              child: Text((dailyInformationAllBean!.data!.fold(0, (value, element) {
                                        if (!element.bGNAME.toString().contains("CXC")) {
                                          return value + element.bLCOST!;
                                        } else {
                                          return value;
                                        }
                                      }) /
                                      dailyInformationAllBean!.data!.fold(0, (value, element) {
                                        if (!element.bGNAME.toString().contains("CXC")) {
                                          return value + element.bLBILLNUM!;
                                        } else {
                                          return value;
                                        }
                                      }))
                                  .toStringAsFixed(1)
                                  .toString())),
                          TableCell(
                              child: Text("${(dailyInformationAllBean!.data!.fold(0, (value, element) {
                                    if (!element.bGNAME.toString().contains("CXC")) {
                                      return value + element.bLCOST!;
                                    } else {
                                      return value;
                                    }
                                  }) / dailyInformationAllBean!.data!.fold(0, (value, element) => value + element.bLCOST! ?? 0) * 100).toStringAsFixed(1).toString()}%")),
                        ]),
                      ],
                    ),
                    ElevatedButton(
                        onPressed: () {
                          dynamic cxcAllSJ = dailyInformationAllBean!.data!.fold(0, (value, element) => value + element.bLCOST! ?? 0);
                          dynamic cxcAllSL = dailyInformationAllBean!.data!.fold(0, (value, element) => value + element.bLBILLNUM!);
                          dynamic cxcAllPJ = (cxcAllSJ / cxcAllSL).toStringAsFixed(1).toString();
                          dynamic cxcZhiKeSJ = dailyInformationAllBean!.data!.fold(0, (value, element) {
                            if (element.bGNAME.toString().contains("CXC")) {
                              return value + element.bLCOST!;
                            } else {
                              return value;
                            }
                          });
                          dynamic cxcZhiKeSL = dailyInformationAllBean!.data!.fold(0, (value, element) {
                            if (element.bGNAME.toString().contains("CXC")) {
                              return value + element.bLBILLNUM!;
                            } else {
                              return value;
                            }
                          });
                          dynamic cxcZhiKePJ = (cxcZhiKeSJ / cxcZhiKeSL).toStringAsFixed(1).toString();

                          dynamic cxcJMSSJ = dailyInformationAllBean!.data!.fold(0, (value, element) {
                            if (!element.bGNAME.toString().contains("CXC")) {
                              return value + element.bLCOST!;
                            } else {
                              return value;
                            }
                          });
                          dynamic cxcJMSSL = dailyInformationAllBean!.data!.fold(0, (value, element) {
                            if (!element.bGNAME.toString().contains("CXC")) {
                              return value + element.bLBILLNUM!;
                            } else {
                              return value;
                            }
                          });
                          dynamic cxcJMSPJ = (cxcJMSSJ / cxcJMSSL).toStringAsFixed(1).toString();

                          String selectDateTime = "${waybillPrintingStart.substring(0, 7)}";

                          "\t${waybillPrintingBean!.data!.fold(0, (value, element) => value + element.bLCOST! ?? 0)}\t${waybillPrintingBean!.data!.fold(0, (value, element) => value + element.bLBILLNUM! ?? 0)}\n"
                                  "${selectDateTime} 月份套票銷售總額\t售價\t套票數量\t平均價/票\n"
                                  "\t${cxcAllSJ}\t${cxcAllSL}\t${cxcAllPJ}\n"
                                  "\n"
                                  "CXC 直客\t $cxcZhiKeSJ\t $cxcZhiKeSL\t $cxcZhiKePJ\t${(dailyInformationAllBean!.data!.fold(0, (value, element) {
                                        if (element.bGNAME.toString().contains("CXC")) {
                                          return value + element.bLCOST!;
                                        } else {
                                          return value;
                                        }
                                      }) / dailyInformationAllBean!.data!.fold(0, (value, element) => value + element.bLCOST! ?? 0) * 100).toStringAsFixed(1).toString()}%\n"
                                  "加盟商\t $cxcJMSSJ\t $cxcJMSSL\t $cxcJMSPJ\t${(dailyInformationAllBean!.data!.fold(0, (value, element) {
                                        if (!element.bGNAME.toString().contains("CXC")) {
                                          return value + element.bLCOST!;
                                        } else {
                                          return value;
                                        }
                                      }) / dailyInformationAllBean!.data!.fold(0, (value, element) => value + element.bLCOST! ?? 0) * 100).toStringAsFixed(1).toString()}%\n"
                              .copyValue();
                        },
                        child: Text("copy")),
                  ],
                ),
              ),
            ],
          ],
        ),
      ],
    );
  }

  _copyAllData() {
    StringBuffer sb = StringBuffer();
    String tempStr = waybillPrintingBean!.data
            ?.map((e) => "${e.bLAPPLYDATE}\t${e.cMCODE}\t${e.bLCOST}\t${e.bLBILLNUM}\t${e.bLPCOST}\t${e.bGNAME}\t${e.bLVALIDITY}\t${e.cMNAME}\t${e.cMADDRESS}")
            .join("\n")
            .toString() ??
        "";
    sb.write(tempStr);
    dynamic cxcAllSJ = dailyInformationAllBean!.data!.fold(0, (value, element) => value + element.bLCOST! ?? 0);
    dynamic cxcAllSL = dailyInformationAllBean!.data!.fold(0, (value, element) => value + element.bLBILLNUM!);
    dynamic cxcAllPJ = (cxcAllSJ / cxcAllSL).toStringAsFixed(1).toString();
    dynamic cxcZhiKeSJ = dailyInformationAllBean!.data!.fold(0, (value, element) {
      if (element.bGNAME.toString().contains("CXC")) {
        return value + element.bLCOST!;
      } else {
        return value;
      }
    });
    dynamic cxcZhiKeSL = dailyInformationAllBean!.data!.fold(0, (value, element) {
      if (element.bGNAME.toString().contains("CXC")) {
        return value + element.bLBILLNUM!;
      } else {
        return value;
      }
    });
    dynamic cxcZhiKePJ = (cxcZhiKeSJ / cxcZhiKeSL).toStringAsFixed(1).toString();
    dynamic cxcJMSSJ = dailyInformationAllBean!.data!.fold(0, (value, element) {
      if (!element.bGNAME.toString().contains("CXC")) {
        return value + element.bLCOST!;
      } else {
        return value;
      }
    });
    dynamic cxcJMSSL = dailyInformationAllBean!.data!.fold(0, (value, element) {
      if (!element.bGNAME.toString().contains("CXC")) {
        return value + element.bLBILLNUM!;
      } else {
        return value;
      }
    });

    String selectYearDateTime = "${waybillPrintingStart.substring(0, 4)}";
    String selectMonthDateTime = "${waybillPrintingStart.substring(5, 7)}";

    dynamic cxcJMSPJ = (cxcJMSSJ / cxcJMSSL).toStringAsFixed(1).toString();
    sb.write("\n"
        // "\n\t\t${waybillPrintingBean!.data!.fold(0, (value, element) => value + element.bLCOST! ?? 0)}\t${waybillPrintingBean!.data!.fold(0, (value, element) => value + element.bLBILLNUM! ?? 0)}\n"
        "\t$selectMonthDateTime/$selectYearDateTime 月份套票銷售總額\t售價\t套票數量\t平均價/票\n"
        "\t\t${cxcAllSJ}\t${cxcAllSL}\t${cxcAllPJ}\n"
        "\n"
        "\tCXC 直客\t $cxcZhiKeSJ\t $cxcZhiKeSL\t $cxcZhiKePJ\t${(dailyInformationAllBean!.data!.fold(0, (value, element) {
              if (element.bGNAME.toString().contains("CXC")) {
                return value + element.bLCOST!;
              } else {
                return value;
              }
            }) / dailyInformationAllBean!.data!.fold(0, (value, element) => value + element.bLCOST! ?? 0) * 100).toStringAsFixed(1).toString()}%\n"
        "\t加盟商\t $cxcJMSSJ\t $cxcJMSSL\t $cxcJMSPJ\t${(dailyInformationAllBean!.data!.fold(0, (value, element) {
              if (!element.bGNAME.toString().contains("CXC")) {
                return value + element.bLCOST!;
              } else {
                return value;
              }
            }) / dailyInformationAllBean!.data!.fold(0, (value, element) => value + element.bLCOST! ?? 0) * 100).toStringAsFixed(1).toString()}%\n");
    sb.toString().copyValue();
  }

  // 日期范围
  Widget calendarDatePicker(
      {bool row = false,
      DateTime? currentStartDate,
      DateTime? currentEndDate,
      required Function(String) startOnDateChanged,
      required Function(String) endOnDateChanged}) {
    Widget startWidget = SizedBox(
      width: 200,
      height: 200,
      child: CalendarDatePicker(
          initialDate: null,
          currentDate: currentStartDate ?? DateTime(year, month, day - 1, 00, 00, 00),
          firstDate: DateTime(2020 - 10, 1, 1, 0, 0, 0),
          lastDate: DateTime(year, month, day, 23, 59, 59),
          onDateChanged: (date) {
            var startTime = "${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')} 00:00:00";
            startOnDateChanged(startTime);
          }),
    );
    Widget endWidget = SizedBox(
      width: 200,
      height: 200,
      child: CalendarDatePicker(
          initialDate: null,
          currentDate: currentEndDate ?? DateTime(year, month, day - 1, 59, 59, 59),
          firstDate: DateTime(2020 - 10, 1, 1, 0, 0, 0),
          lastDate: DateTime(year, month, day, 23, 59, 59),
          onDateChanged: (date) {
            var endTime = "${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')} 23:59:59";
            endOnDateChanged(endTime);
          }),
    );
    if (row) {
      return Row(children: [startWidget, endWidget]);
    } else {
      return Column(children: [startWidget, endWidget]);
    }
  }

  // 表字符
  TableRow tabRows(List<String> tabLabels, {Color? textColor}) {
    return TableRow(children: tabLabels.map((e) => TableCell(child: Center(child: Text(e, style: TextStyle(color: textColor ?? Colors.black))))).toList());
  }

  // 表Widget
  TableRow tabRowWidgets(List<Widget> tabLabels) {
    return TableRow(children: tabLabels.map((e) => TableCell(child: e)).toList());
  }

  Widget copyWidget(Widget text) {
    return Center(
      child: InkWell(
        onTap: () {
          (text as Text).data?.copyValue();
        },
        child: text,
      ),
    );
  }

  Widget _dateWidget({required String startTime, required String endTime, required dataCount}) {
    return Text.rich(TextSpan(children: [
      TextSpan(text: "查询的日期："),
      TextSpan(text: "${startTime} - ${endTime}", style: TextStyle(color: Colors.red, fontSize: 16)),
      TextSpan(text: "共有${dataCount}条数据"),
    ]));
  }

  Widget _localDeliveryStatisticsWidget(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Column(
          children: [
            IconButton(
              onPressed: () {
                if (localDeliveryStatisticsLoading) return;
                dailyReportBloc?.add(DailyReportLocalDeliveryStatisticsDataEvent(startDate: localDeliveryStatisticsStart, endDate: localDeliveryStatisticsEnd));
              },
              icon: AnimatedSwitcher(
                  duration: Duration(seconds: 1),
                  child: localDeliveryStatisticsLoading
                      ? SizedBox(key: ValueKey("loading"), width: 40, height: 40, child: CircularProgressIndicator())
                      : const SizedBox(
                          key: ValueKey("search"),
                          height: 40,
                          child: Row(children: [Icon(Icons.search, color: Colors.green), Text("查询 同城本地簽收統計", style: TextStyle(color: Colors.green))]))),
            ),
            CalendarView(
              day: 1,
              onInitDateChanged: (startDateTime, startStr, endDateTime, endStr) {
                localDeliveryStatisticsStart = "${startStr}";
                localDeliveryStatisticsEnd = "${endStr}";
              },
              onDateStartChanged: (startDateTime, startStr) {
                print("disMonthFeeStartDate: $startDateTime, $startStr");
                localDeliveryStatisticsStart = "${startStr}";
              },
              onDateEndChanged: (endDateTime, endStr) {
                print("disMonthFeeEndDate: $endDateTime, $endStr");
                localDeliveryStatisticsEnd = "${endStr}";
              },
            ),
          ],
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (localDeliveryStatisticsBean != null && localDeliveryStatisticsBean?.status == 1) ...[
              Row(
                children: [
                  TextButton(
                      onPressed: () {
                        StringBuffer sbDayTGT1 = StringBuffer();
                        dynamic t1 = localDeliveryStatisticsBean!.data!
                            .map((e) =>
                                "${e.sCANDATE}\t${e.lOCALBUSSINS}\t${e.sIGNSAMECITY}\t${e.sIGNRATESAMECITY}\t${e.oNLINEBUSSINS}\t${e.sIGNONLINE}\t${e.sIGNRATEONLINE}\t${e.cOUNTBUSSINS}\t${e.sIGNCOUNT}\t${e.sIGNCOUNTONLINE}")
                            .join("\n")
                            .toString();
                        sbDayTGT1.write(t1);
                        sbDayTGT1.write("\n合計\t"
                            "${localDeliveryStatisticsBean!.data!.fold(0, (value, e) => value + e.lOCALBUSSINS!)}\t"
                            "${localDeliveryStatisticsBean!.data!.fold(0, (value, e) => value + e.sIGNSAMECITY!)}\t"
                            "${localDeliveryStatisticsBean!.data!.fold(0, (value, e) => value + e.sIGNSAMECITY!) / localDeliveryStatisticsBean!.data!.fold(0, (value, e) => value + e.lOCALBUSSINS!)}\t"
                            "${localDeliveryStatisticsBean!.data!.fold(0, (value, e) => value + e.oNLINEBUSSINS!)}\t"
                            "${localDeliveryStatisticsBean!.data!.fold(0, (value, e) => value + e.sIGNONLINE!)}\t"
                            "${localDeliveryStatisticsBean!.data!.fold(0, (value, e) => value + e.sIGNONLINE!) / localDeliveryStatisticsBean!.data!.fold(0, (value, e) => value + e.oNLINEBUSSINS!)}\t"
                            "${localDeliveryStatisticsBean!.data!.fold(0, (value, e) => value + e.cOUNTBUSSINS!)}\t"
                            "${localDeliveryStatisticsBean!.data!.fold(0, (value, e) => value + e.sIGNCOUNT!)}\t"
                            "${localDeliveryStatisticsBean!.data!.fold(0, (value, e) => value + e.sIGNCOUNT!) / localDeliveryStatisticsBean!.data!.fold(0, (value, e) => value + e.cOUNTBUSSINS!)}");

                        sbDayTGT1.toString().copyValue();
                      },
                      child: Text("C表1")),
                  TextButton(
                      onPressed: () {
                        // 改为C最后一行数据
                        var e = localDeliveryStatisticsBean!.data!.last;
                        """${e.sCANDATE}\t${e.lOCALBUSSINS}\t${e.sIGNSAMECITY}\t${e.sIGNRATESAMECITY}\t${e.oNLINEBUSSINS}\t${e.sIGNONLINE}\t${e.sIGNRATEONLINE}\t${e.cOUNTBUSSINS}\t${e.sIGNCOUNT}\t${e.sIGNCOUNTONLINE}"""
                            .copyValue();
                      },
                      child: const Text("C表1 最后一行")),
                ],
              ),
              Table(
                border: TableBorder.all(color: Colors.black),
                children: [
                  tabRows(["入场时间", "本地件入場(同城)", "簽收(同城)", "簽收率(同城)", "電商件入場", "簽收(電商)", "簽收率(電商件)", "總件數(入場)", "簽收(整體)", "總簽收率"]),
                  ...localDeliveryStatisticsBean!.data!.map((e) => TableRow(children: [
                        TableCell(child: Text(e.sCANDATE.toString())),
                        TableCell(child: Text(e.lOCALBUSSINS.toString())),
                        TableCell(child: Text(e.sIGNSAMECITY.toString())),
                        TableCell(child: Text(e.sIGNRATESAMECITY.toString())),
                        TableCell(child: Text(e.oNLINEBUSSINS.toString())),
                        TableCell(child: Text(e.sIGNONLINE.toString())),
                        TableCell(child: Text(e.sIGNRATEONLINE.toString())),
                        TableCell(child: Text(e.cOUNTBUSSINS.toString())),
                        TableCell(child: Text(e.sIGNCOUNT.toString())),
                        TableCell(child: Text(e.sIGNCOUNTONLINE.toString())),
                      ])),
                  tabRowWidgets([
                    Text("合计", style: TextStyle(color: Colors.red)),
                    Text("${localDeliveryStatisticsBean!.data?.fold(0, (value, element) => value + (element.lOCALBUSSINS ?? 0))}",
                        style: TextStyle(color: Colors.red)),
                    Text("${localDeliveryStatisticsBean!.data?.fold(0, (value, element) => value + (element.sIGNSAMECITY ?? 0))}",
                        style: TextStyle(color: Colors.red)),
                    Text(
                        "${(localDeliveryStatisticsBean!.data!.fold(0, (value, element) => value + (element.sIGNSAMECITY ?? 0)).toDouble() / (localDeliveryStatisticsBean!.data!.fold(0, (value, element) => value + (element.lOCALBUSSINS ?? 0)).toDouble()) * 100).toStringAsFixed(2)}%",
                        style: TextStyle(color: Colors.red)),
                    Text("${localDeliveryStatisticsBean!.data?.fold(0, (value, element) => value + (element.oNLINEBUSSINS ?? 0))}",
                        style: TextStyle(color: Colors.red)),
                    Text("${localDeliveryStatisticsBean!.data?.fold(0, (value, element) => value + (element.sIGNONLINE ?? 0))}",
                        style: TextStyle(color: Colors.red)),
                    Text(
                        "${(localDeliveryStatisticsBean!.data!.fold(0, (value, element) => value + (element.sIGNONLINE ?? 0)).toDouble() / (localDeliveryStatisticsBean!.data!.fold(0, (value, element) => value + (element.oNLINEBUSSINS ?? 0)).toDouble()) * 100).toStringAsFixed(2)}%",
                        style: TextStyle(color: Colors.red)),
                    Text("${localDeliveryStatisticsBean!.data?.fold(0, (value, element) => value + (element.cOUNTBUSSINS ?? 0))}",
                        style: TextStyle(color: Colors.red)),
                    Text("${localDeliveryStatisticsBean!.data?.fold(0, (value, element) => value + (element.sIGNCOUNT ?? 0))}",
                        style: TextStyle(color: Colors.red)),
                    Text(
                        "${(localDeliveryStatisticsBean!.data!.fold(0, (value, element) => value + (element.sIGNCOUNT ?? 0)).toDouble() / (localDeliveryStatisticsBean!.data!.fold(0, (value, element) => value + (element.cOUNTBUSSINS ?? 0)).toDouble()) * 100).toStringAsFixed(2)}%",
                        style: TextStyle(color: Colors.red)),
                  ]),
                ],
              ),
            ],
            if (independentStatisticalBean != null && independentStatisticalBean?.status == 1) ...[
              Row(
                children: [
                  TextButton(
                      onPressed: () {
                        StringBuffer sbDayTGT2 = StringBuffer();
                        dynamic t2 = independentStatisticalBean!.data!
                            .map((e) =>
                                "${e.dateTime}\t${e.rINCOS}\t${e.OCSShou}\t${e.OCSPai}\t${e.jiuheng}\t${e.Konica}\t${e.gODWELL}\t${e.consolidationTransportation}\t${e.lX}\t${e.sASA}\t${e.otherIt}\t${e.total}")
                            .join("\n");
                        sbDayTGT2.write(t2);
                        sbDayTGT2.write("\n合計\t"
                            "${independentStatisticalBean!.data!.fold(0, (value, e) => value + e.rINCOS!)}\t"
                            "${independentStatisticalBean!.data!.fold(0, (value, e) => value + e.OCSShou!)}\t"
                            "${independentStatisticalBean!.data!.fold(0, (value, e) => value + e.OCSPai!)}\t"
                            "${independentStatisticalBean!.data!.fold(0, (value, e) => value + e.jiuheng!)}\t"
                            "${independentStatisticalBean!.data!.fold(0, (value, e) => value + e.Konica!)}\t"
                            "${independentStatisticalBean!.data!.fold(0, (value, e) => value + e.gODWELL!)}\t"
                            "${independentStatisticalBean!.data!.fold(0, (value, e) => value + e.consolidationTransportation!)}\t"
                            "${independentStatisticalBean!.data!.fold(0, (value, e) => value + e.lX!)}\t"
                            "${independentStatisticalBean!.data!.fold(0, (value, e) => value + e.sASA!)}\t"
                            "${independentStatisticalBean!.data!.fold(0, (value, e) => value + e.otherIt!)}\t"
                            "${independentStatisticalBean!.data!.fold(0, (value, e) => value + e.total!)}\t");
                        sbDayTGT2.toString().copyValue();
                      },
                      child: Text("C電商件入場數細分")),
                  TextButton(
                      onPressed: () {
                        var e = independentStatisticalBean!.data!.last;
                        """${e.dateTime}\t${e.rINCOS}\t${e.OCSShou}\t${e.OCSPai}\t${e.jiuheng}\t${e.Konica}\t${e.gODWELL}\t${e.consolidationTransportation}\t${e.lX}\t${e.sASA}\t${e.otherIt}\t${e.total}"""
                            .copyValue();
                      },
                      child: Text("C電商件入場數細分 最后一行")),
                ],
              ),
              Table(
                border: TableBorder.all(color: Colors.black),
                children: [
                  tabRows(["日期", "Rincos", "OCS收", "OCS派", "九恆", "Konica", "Godwell", "CXC集運", "LX", "SASA", "其它", "合計"]),
                  ...independentStatisticalBean!.data!.map((e) => TableRow(children: [
                        TableCell(child: Text(e.dateTime.toString())),
                        TableCell(child: Text(e.rINCOS.toString())),
                        TableCell(child: Text(e.OCSShou.toString())),
                        TableCell(child: Text(e.OCSPai.toString())),
                        TableCell(child: Text(e.jiuheng.toString())),
                        TableCell(child: Text(e.Konica.toString())),
                        TableCell(child: Text(e.gODWELL.toString())),
                        TableCell(child: Text(e.consolidationTransportation.toString())),
                        TableCell(child: Text(e.lX.toString())),
                        TableCell(child: Text(e.sASA.toString())),
                        TableCell(child: Text(e.otherIt.toString())),
                        TableCell(child: Text(e.total.toString())),
                      ])),
                  tabRowWidgets([
                    Text("合计", style: TextStyle(color: Colors.red)),
                    Text("${independentStatisticalBean!.data?.fold(0, (value, element) => value + (element.rINCOS ?? 0))}",
                        style: TextStyle(color: Colors.red)),
                    Text("${independentStatisticalBean!.data?.fold(0, (value, element) => value + (element.OCSShou ?? 0))}",
                        style: TextStyle(color: Colors.red)),
                    Text("${independentStatisticalBean!.data?.fold(0, (value, element) => value + (element.OCSPai ?? 0))}",
                        style: TextStyle(color: Colors.red)),
                    Text("${independentStatisticalBean!.data?.fold(0, (value, element) => value + (element.jiuheng ?? 0))}",
                        style: TextStyle(color: Colors.red)),
                    Text("${independentStatisticalBean!.data?.fold(0, (value, element) => value + (element.Konica ?? 0))}",
                        style: TextStyle(color: Colors.red)),
                    Text("${independentStatisticalBean!.data?.fold(0, (value, element) => value + (element.gODWELL ?? 0))}",
                        style: TextStyle(color: Colors.red)),
                    Text("${independentStatisticalBean!.data?.fold(0, (value, element) => value + (element.consolidationTransportation ?? 0))}",
                        style: TextStyle(color: Colors.red)),
                    Text("${independentStatisticalBean!.data?.fold(0, (value, element) => value + (element.lX ?? 0))}", style: TextStyle(color: Colors.red)),
                    Text("${independentStatisticalBean!.data?.fold(0, (value, element) => value + (element.sASA ?? 0))}", style: TextStyle(color: Colors.red)),
                    Text("${independentStatisticalBean!.data?.fold(0, (value, element) => value + (element.otherIt ?? 0))}",
                        style: TextStyle(color: Colors.red)),
                    Text("${independentStatisticalBean!.data?.fold(0, (value, element) => value + (element.total ?? 0))}", style: TextStyle(color: Colors.red))
                  ]),
                ],
              ),
            ]
          ],
        ),
      ],
    );
  }

  // CMS 票數表
  Widget _cmsTicketWidget(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              width: 200,
              height: 40,
              child: IconButton(
                onPressed: () {
                  if (cmsTicketLoading) return;
                  dailyReportBloc?.add(CmsTicketDataEvent(startDate: cmsTicketStart, endDate: cmsTicketEnd));
                },
                icon: AnimatedSwitcher(
                    duration: const Duration(seconds: 1),
                    child: cmsTicketLoading
                        ? const SizedBox(key: ValueKey("loading"), width: 40, height: 40, child: CircularProgressIndicator())
                        : const SizedBox(
                            key: ValueKey("search"),
                            height: 40,
                            child: Row(children: [Icon(Icons.search, color: Colors.green), Text("查询CMS 票數表", style: TextStyle(color: Colors.green))]))),
              ),
            ),
            CalendarView(
              day: 1,
              onInitDateChanged: (startDateTime, startStr, endDateTime, endStr) {
                cmsTicketStart = "${startStr}";
                cmsTicketEnd = "${endStr}";
              },
              onDateStartChanged: (startDateTime, startStr) {
                cmsTicketStart = "${startStr}";
              },
              onDateEndChanged: (endDateTime, endStr) {
                cmsTicketEnd = "${endStr}";
              },
            ),
          ],
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (cmsTicketBean != null && cmsTicketBean?.status == 1 && cmsTicketBean!.data!.isNotEmpty) ...[
              Text.rich(TextSpan(children: [
                TextSpan(text: "查询的日期："),
                TextSpan(text: "${cmsTicketStart} - ${cmsTicketEnd}", style: TextStyle(color: Colors.red, fontSize: 16)),
                TextSpan(text: "共有${cmsTicketBean!.data!.length}条数据"),
              ])),
              Row(
                children: [
                  TextButton(
                      onPressed: () {
                        StringBuffer sb = StringBuffer();
                        sb.write(cmsTicketBean!.data!
                            .map((e) =>
                                "${e.gROUPDATE}\t${e.tCCOUNT}\t${e.cMSCOUNT}\t${e.cITYCOUNT}\t${e.aCSCOUNT}\t${e.dSCOUNT}\t${e.aLLCOUNT}\t\t${(e.no9821229 == 0 || e.no9821229 == 1 || e.no9821229 == null) ? "" : e.no9821229}\t${(e.no9821190 == 0 || e.no9821190 == 1 || e.no9821190 == null) ? "" : e.no9821190}")
                            .join("\n")
                            .toString());
                        sb.write("\n\t");
                        sb.write("${cmsTicketBean!.data!.fold(0, (value, element) => value + (element.tCCOUNT ?? 0))}\t"
                            "${cmsTicketBean!.data!.fold(0, (value, element) => value + (element.cMSCOUNT ?? 0))}\t"
                            "${cmsTicketBean!.data!.fold(0, (value, element) => value + (element.cITYCOUNT ?? 0))}\t"
                            "${cmsTicketBean!.data!.fold(0, (value, element) => value + (element.aCSCOUNT ?? 0))}\t"
                            "${cmsTicketBean!.data!.fold(0, (value, element) => value + (element.dSCOUNT ?? 0))}\t"
                            "${cmsTicketBean!.data!.fold(0, (value, element) => value + (element.aLLCOUNT ?? 0))}\t"
                            "\t"
                            "${cmsTicketBean!.data!.fold(0, (value, element) => value + (element.no9821229 ?? 0)) == 0 ? "" : cmsTicketBean!.data!.fold(0, (value, element) => value + (element.no9821229 ?? 0))}\t"
                            "${cmsTicketBean!.data!.fold(0, (value, element) => value + (element.no9821190 ?? 0)) == 0 ? "" : cmsTicketBean!.data!.fold(0, (value, element) => value + (element.no9821190 ?? 0))}\t");
                        sb.toString().copyValue();
                      },
                      child: Text("CCMS 票數表")),
                  TextButton(
                      onPressed: () {
                        var e = cmsTicketBean!.data!.last;
                        """${e.gROUPDATE}\t${e.tCCOUNT}\t${e.cMSCOUNT}\t${e.cITYCOUNT}\t${e.aCSCOUNT}\t${e.dSCOUNT}\t${e.aLLCOUNT}\t\t${e.no9821229 ?? ""}\t${e.no9821190 ?? ""}"""
                            .copyValue();
                      },
                      child: Text("CCMS 票數表 最后一行")),
                ],
              ),
              Table(
                border: TableBorder.all(color: Colors.black),
                children: [
                  tabRows(["日期", "同城件票數", "內含CMS", "內含城市", "內含ACS", "電商件票數", "全公司整體票數", "", "G3 (9821229)", "ECMS (9821190)"]),
                  ...cmsTicketBean!.data!.map((e) => TableRow(children: [
                        TableCell(child: Text(e.gROUPDATE.toString())),
                        TableCell(child: Text(e.tCCOUNT.toString())),
                        TableCell(child: Text(e.cMSCOUNT.toString())),
                        TableCell(child: Text(e.cITYCOUNT.toString())),
                        TableCell(child: Text(e.aCSCOUNT.toString())),
                        TableCell(child: Text(e.dSCOUNT.toString())),
                        TableCell(child: Text(e.aLLCOUNT.toString())),
                        const TableCell(child: Text("")),
                        TableCell(child: Text("${e.no9821229 == null || e.no9821229 == 0 || e.no9821229 == 1 ? "" : e.no9821229}")),
                        TableCell(child: Text("${e.no9821190 == null || e.no9821190 == 0 || e.no9821190 == 1 ? "" : e.no9821190}")),
                      ])),
                  tabRowWidgets([
                    const Text(""),
                    copyWidget(
                        Text("${cmsTicketBean!.data!.fold(0, (value, element) => value + (element.tCCOUNT ?? 0))}", style: TextStyle(color: Colors.red))),
                    copyWidget(
                        Text("${cmsTicketBean!.data!.fold(0, (value, element) => value + (element.cMSCOUNT ?? 0))}", style: TextStyle(color: Colors.red))),
                    copyWidget(
                        Text("${cmsTicketBean!.data!.fold(0, (value, element) => value + (element.cITYCOUNT ?? 0))}", style: TextStyle(color: Colors.red))),
                    copyWidget(
                        Text("${cmsTicketBean!.data!.fold(0, (value, element) => value + (element.aCSCOUNT ?? 0))}", style: TextStyle(color: Colors.red))),
                    copyWidget(
                        Text("${cmsTicketBean!.data!.fold(0, (value, element) => value + (element.dSCOUNT ?? 0))}", style: TextStyle(color: Colors.red))),
                    copyWidget(
                        Text("${cmsTicketBean!.data!.fold(0, (value, element) => value + (element.aLLCOUNT ?? 0))}", style: TextStyle(color: Colors.red))),
                    copyWidget(const Text("", style: TextStyle(color: Colors.red))),
                    copyWidget(
                        Text("${cmsTicketBean!.data!.fold(0, (value, element) => value + (element.no9821229 ?? 0))}", style: TextStyle(color: Colors.red))),
                    copyWidget(
                        Text("${cmsTicketBean!.data!.fold(0, (value, element) => value + (element.no9821190 ?? 0))}", style: TextStyle(color: Colors.red))),
                  ]),
                ],
              ),
            ],
          ],
        ),
      ],
    );
  }

  Widget _specifyCustomerWidget(BuildContext context) {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                child: IconButton(
                  onPressed: () {
                    if (specifyCustomerLoading) return;
                    dailyReportBloc?.add(SpecifyCustomerEvent(
                        startDate: specifyCustomerStart,
                        endDate: specifyCustomerEnd,
                        specifyCustomerCurrentMonth: specifyCustomerCurrentMonth!,
                        customerNo: customerNo));
                  },
                  icon: AnimatedSwitcher(
                      duration: const Duration(seconds: 1),
                      child: specifyCustomerLoading
                          ? const SizedBox(key: ValueKey("loading"), width: 40, height: 40, child: CircularProgressIndicator())
                          : const SizedBox(
                              key: ValueKey("search"),
                              height: 40,
                              child: Row(children: [Icon(Icons.search, color: Colors.red), Text("查询指定客户统计", style: TextStyle(color: Colors.green))]))),
                ),
              ),
              calendarDatePicker(
                  row: true,
                  currentStartDate: DateTime.parse(specifyCustomerStart),
                  currentEndDate: DateTime.parse(specifyCustomerEnd),
                  startOnDateChanged: (value) {
                    specifyCustomerStart = value;
                  },
                  endOnDateChanged: (value) {
                    specifyCustomerEnd = value;
                  }),
              CheckboxListTile(
                  value: specifyCustomerCurrentMonth,
                  onChanged: (value) {
                    setState(() {
                      specifyCustomerCurrentMonth = value;
                    });
                  },
                  title: Text("查询当前月份"))
            ],
          ),
        ],
      ),
    );
  }

  Widget _signStatisticsWidget(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(
              width: 200,
              child: IconButton(
                onPressed: () {
                  if (signStatisticsLoading) return;
                  var startDate15Time = DateTime.parse(signStatisticsStart).subtract(Duration(days: 14));
                  String startDate15 =
                      "${startDate15Time.year}-${startDate15Time.month.toString().padLeft(2, '0')}-${(startDate15Time.day).toString().padLeft(2, '0')} 00:00:00";
                  dailyReportBloc?.add(SignStatisticsEvent(startDate: signStatisticsStart, endDate: signStatisticsEnd, startDate15: startDate15));
                },
                icon: AnimatedSwitcher(
                    duration: const Duration(seconds: 1),
                    child: signStatisticsLoading
                        ? const SizedBox(key: ValueKey("loading"), width: 40, height: 40, child: CircularProgressIndicator())
                        : const SizedBox(
                            key: ValueKey("search"),
                            height: 40,
                            child: Row(children: [Icon(Icons.search, color: Colors.green), Text("查询签收统计", style: TextStyle(color: Colors.green))]))),
              ),
            ),
            CalendarView(
              onInitDateChanged: (startDateTime, startStr, endDateTime, endStr) {
                signStatisticsStart = "${startStr}";
                signStatisticsEnd = "${endStr}";
              },
              onDateStartChanged: (startDateTime, startStr) {
                signStatisticsStart = "${startStr}";
              },
              onDateEndChanged: (endDateTime, endStr) {
                signStatisticsEnd = "${endStr}";
              },
            ),
          ],
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (signStatistics.isNotEmpty) ...[
              ...signStatistics.map((mapSignStatistics) {
                String label = mapSignStatistics["label"];
                String signStatistics = mapSignStatistics["signStatistics"];
                String searchDateTime = mapSignStatistics["searchDateTime"];
                if (label == "98") {
                  String totalCountNotAppearing98 = mapSignStatistics["totalCountNotAppearing98"];
                  String totalCountAlreadyAppearing98 = mapSignStatistics["totalCountAlreadyAppearing98"];
                  return Container(
                    decoration: BoxDecoration(border: Border.all(color: Colors.black, width: 1)),
                    margin: EdgeInsets.only(top: 10),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          "时间：${searchDateTime}",
                          style: const TextStyle(fontSize: 16),
                        ),
                        Row(
                          children: [
                            GestureDetector(
                                onTap: () {
                                  totalCountNotAppearing98.copyValue();
                                },
                                child: Text(
                                  "客户编号：${label}      , 总数量：${signStatistics}",
                                  style: const TextStyle(fontSize: 16),
                                )),
                            SizedBox(
                              width: 20,
                            ),
                            Text.rich(TextSpan(style: const TextStyle(fontSize: 16), children: [
                              TextSpan(text: "二樓未出場数量："),
                              TextSpan(
                                  text: totalCountNotAppearing98,
                                  style: const TextStyle(color: Colors.red, decoration: TextDecoration.underline),
                                  recognizer: TapGestureRecognizer()
                                    ..onTap = () {
                                      totalCountNotAppearing98.copyValue();
                                    }),
                              TextSpan(text: "\n    已出场数量："),
                              TextSpan(
                                  text: totalCountAlreadyAppearing98,
                                  style: const TextStyle(color: Colors.red, decoration: TextDecoration.underline),
                                  recognizer: TapGestureRecognizer()
                                    ..onTap = () {
                                      totalCountAlreadyAppearing98.copyValue();
                                    }),
                            ])),
                          ],
                        ),
                      ],
                    ),
                  );
                } else {
                  return GestureDetector(
                    child: Container(
                      margin: EdgeInsets.only(top: 10),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            "时间：${searchDateTime}",
                            style: const TextStyle(fontSize: 16),
                          ),
                          Text.rich(TextSpan(style: const TextStyle(fontSize: 16), children: [
                            TextSpan(text: "客户编号："),
                            TextSpan(text: "${label}   ", style: TextStyle(color: Colors.blue, fontSize: 16)),
                            TextSpan(text: "总数量："),
                            TextSpan(
                                text: signStatistics,
                                style: const TextStyle(color: Colors.red, decoration: TextDecoration.underline),
                                recognizer: TapGestureRecognizer()
                                  ..onTap = () {
                                    signStatistics.copyValue();
                                  }),
                          ])),
                        ],
                      ),
                    ),
                  );
                }
              }),
            ],
            TextButton(
              onPressed: () {
                StringBuffer sb = StringBuffer();
                // 签收统计
                for (var mapSignStatistics in signStatistics) {
                  String label = mapSignStatistics["label"];
                  String signStatistics = mapSignStatistics["signStatistics"];
                  String searchDateTime = mapSignStatistics["searchDateTime"];
                  String showDateTime = mapSignStatistics["showDateTime"];
                  if (label == "98") {
                    String totalCountNotAppearing98 = mapSignStatistics["totalCountNotAppearing98"];
                    String totalCountAlreadyAppearing98 = mapSignStatistics["totalCountAlreadyAppearing98"];
                    // 时间
                    searchDateTime;
                    showDateTime;
                    // String signStatisticsStr = "客户编号：${label}      , 总数量：${signStatistics}";
                    // String totalCountStr = "二樓未出場数量：${totalCountNotAppearing98}    \n已出場数量：${totalCountAlreadyAppearing98}";
                    sb.write("$showDateTime\t$totalCountAlreadyAppearing98\t\t$totalCountNotAppearing98\t二樓未出場\t$totalCountNotAppearing98\n");
                    sb.write("\t\t\t\t二樓待處理問題件/巳上架\t0\n");
                    sb.write("\t\t\t\t巳掃上板待退客倉\t0\n");
                  }
                  // else {
                  //   String signStatisticsStr = "客户编号：$label  总数量：$signStatistics";
                  //   sb.write("$showDateTime\n\n$signStatisticsStr\n");
                  // }
                }
                sb.toString().copyValue();
              },
              child: Text("C签收统计"),
            ),
          ],
        ),
      ],
    );
  }

  Widget _dailyVoteWidget(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Column(
          children: [
            IconButton(
              onPressed: () {
                if (dailyVoteLoading) return;
                dailyReportBloc?.add(DailyVoteDataEvent(startDate: dailyVoteStart, endDate: dailyVoteEnd));
              },
              icon: AnimatedSwitcher(
                  duration: const Duration(seconds: 1),
                  child: dailyVoteLoading
                      ? const SizedBox(key: ValueKey("loading"), width: 40, height: 40, child: CircularProgressIndicator())
                      : const SizedBox(
                          key: ValueKey("search"),
                          height: 40,
                          child: Row(children: [Icon(Icons.search, color: Colors.green), Text("查询每天票數統計", style: TextStyle(color: Colors.green))]))),
            ),
            CalendarView(
              day: 1,
              onInitDateChanged: (startDateTime, startStr, endDateTime, endStr) {
                dailyVoteStart = "${startStr}";
                dailyVoteEnd = "${endStr}";
              },
              onDateStartChanged: (startDateTime, startStr) {
                dailyVoteStart = "${startStr}";
              },
              onDateEndChanged: (endDateTime, endStr) {
                dailyVoteEnd = "${endStr}";
              },
            ),
          ],
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (dailyVoteBean != null && dailyVoteBean?.status == 1) ...[
              _dateWidget(startTime: '$dailyVoteStart', endTime: '$dailyVoteEnd', dataCount: dailyVoteBean!.data!.length),
              Row(
                children: [
                  TextButton(
                      onPressed: () {
                        StringBuffer sbDayPSTJ = StringBuffer();
                        sbDayPSTJ.write(dailyVoteBean!.data
                            ?.map((e) =>
                                "${e.bISCANDATE}\t${e.cN}\t${e.yFZK}\t${e.tPZK}\t${e.zGZK}\t${e.sKZK}\t${e.zKHJ}\t${e.zKBL}\t${e.yFJM}\t${e.tPJM}\t${e.zGJM}\t${e.sKJM}\t${e.jMHJ}\t${e.jMBL}")
                            .join("\n"));

                        sbDayPSTJ.write("\n\t"
                            "${dailyVoteBean!.data!.fold(0, (value, e) => value + e.cN!)}\t"
                            "${dailyVoteBean!.data!.fold(0, (value, e) => value + e.yFZK!)}\t"
                            "${dailyVoteBean!.data!.fold(0, (value, e) => value + e.tPZK!)}\t"
                            "${dailyVoteBean!.data!.fold(0, (value, e) => value + e.zGZK!)}\t"
                            "${dailyVoteBean!.data!.fold(0, (value, e) => value + e.sKZK!)}\t"
                            "${dailyVoteBean!.data!.fold(0, (value, e) => value + e.zKHJ!)}\t"
                            "${((dailyVoteBean!.data!.fold(0, (value, e) => value + e.zKHJ!) / dailyVoteBean!.data!.fold(0, (value, e) => value + e.cN!)) * 100).toStringAsFixed(2)}%\t"
                            "${dailyVoteBean!.data!.fold(0, (value, e) => value + e.yFJM!)}\t"
                            "${dailyVoteBean!.data!.fold(0, (value, e) => value + e.tPJM!)}\t"
                            "${dailyVoteBean!.data!.fold(0, (value, e) => value + e.zGJM!)}\t"
                            "${dailyVoteBean!.data!.fold(0, (value, e) => value + e.sKJM!)}\t"
                            "${dailyVoteBean!.data!.fold(0, (value, e) => value + e.jMHJ!)}\t"
                            "${(dailyVoteBean!.data!.fold(0, (value, e) => value + e.jMHJ!) / dailyVoteBean!.data!.fold(0, (value, e) => value + e.cN!) * 100).toStringAsFixed(2)}%\n");
                        sbDayPSTJ.toString().copyValue();
                      },
                      child: Text("C每天票數統計")),
                  TextButton(
                      onPressed: () {
                        var e = dailyVoteBean!.data!.last;
                        """${e.bISCANDATE}\t${e.cN}\t${e.yFZK}\t${e.tPZK}\t${e.zGZK}\t${e.sKZK}\t${e.zKHJ}\t${e.zKBL}\t${e.yFJM}\t${e.tPJM}\t${e.zGJM}\t${e.sKJM}\t${e.jMHJ}\t${e.jMBL}"""
                            .copyValue();
                      },
                      child: Text("C每天票數統計 最后一行")),
                ],
              ),
              Table(
                border: TableBorder.all(color: Colors.black),
                children: [
                  tabRows(["日期", "同城件合計", "月費客", "套票客", "中國客", "散客", "直客合計", "直客運單比例", "月費客", "套票客", "中國客", "散客", "加盟商合計", "加盟商運單比例"]),
                  ...dailyVoteBean!.data!.map((e) => TableRow(children: [
                        TableCell(child: Text(e.bISCANDATE.toString())),
                        TableCell(child: Text(e.cN.toString())),
                        TableCell(child: Text(e.yFZK.toString())),
                        TableCell(child: Text(e.tPZK.toString())),
                        TableCell(child: Text(e.zGZK.toString())),
                        TableCell(child: Text(e.sKZK.toString())),
                        TableCell(child: Text(e.zKHJ.toString())),
                        TableCell(child: Text(e.zKBL.toString())),
                        TableCell(child: Text(e.yFJM.toString())),
                        TableCell(child: Text(e.tPJM.toString())),
                        TableCell(child: Text(e.zGJM.toString())),
                        TableCell(child: Text(e.sKJM.toString())),
                        TableCell(child: Text(e.jMHJ.toString())),
                        TableCell(child: Text(e.jMBL.toString())),
                      ])),
                  tabRows([
                    "合计",
                    "${dailyVoteBean!.data!.fold(0, (value, e) => value + e.cN!)}",
                    "${dailyVoteBean!.data!.fold(0, (value, e) => value + e.yFZK!)}",
                    "${dailyVoteBean!.data!.fold(0, (value, e) => value + e.tPZK!)}",
                    "${dailyVoteBean!.data!.fold(0, (value, e) => value + e.zGZK!)}",
                    "${dailyVoteBean!.data!.fold(0, (value, e) => value + e.sKZK!)}",
                    "${dailyVoteBean!.data!.fold(0, (value, e) => value + e.zKHJ!)}",
                    "${((dailyVoteBean!.data!.fold(0, (value, e) => value + e.zKHJ!) / dailyVoteBean!.data!.fold(0, (value, e) => value + e.cN!)) * 100).toStringAsFixed(2)}%",
                    "${dailyVoteBean!.data!.fold(0, (value, e) => value + e.yFJM!)}",
                    "${dailyVoteBean!.data!.fold(0, (value, e) => value + e.tPJM!)}",
                    "${dailyVoteBean!.data!.fold(0, (value, e) => value + e.zGJM!)}",
                    "${dailyVoteBean!.data!.fold(0, (value, e) => value + e.sKJM!)}",
                    "${dailyVoteBean!.data!.fold(0, (value, e) => value + e.jMHJ!)}",
                    "${(dailyVoteBean!.data!.fold(0, (value, e) => value + e.jMHJ!) / dailyVoteBean!.data!.fold(0, (value, e) => value + e.cN!) * 100).toStringAsFixed(2)}%",
                  ], textColor: Colors.red),
                ],
              ),
            ],
          ],
        ),
      ],
    );
  }

  Widget _topThirtyWidget(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Column(
          children: [
            IconButton(
              onPressed: () {
                if (otherTopThirtyLoading) return;
                dailyReportBloc?.add(OtherTopThirtyDataEvent(startDate: topThirtyStart, endDate: topThirtyEnd));
              },
              icon: AnimatedSwitcher(
                  duration: Duration(seconds: 1),
                  child: otherTopThirtyLoading
                      ? SizedBox(key: ValueKey("loading"), width: 40, height: 40, child: CircularProgressIndicator())
                      : const SizedBox(
                          key: ValueKey("search"),
                          height: 40,
                          child: Row(children: [Icon(Icons.search, color: Colors.green), Text("查询首三十", style: TextStyle(color: Colors.green))]))),
            ),
            CalendarView(
              day: 1,
              onInitDateChanged: (startDateTime, startStr, endDateTime, endStr) {
                topThirtyStart = "${startStr}";
                topThirtyEnd = "${endStr}";
              },
              onDateStartChanged: (startDateTime, startStr) {
                topThirtyStart = "${startStr}";
              },
              onDateEndChanged: (endDateTime, endStr) {
                topThirtyEnd = "${endStr}";
              },
            ),
          ],
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (otherTopThirtyBean != null && otherTopThirtyBean?.status == 1) ...[
              _dateWidget(startTime: '$topThirtyStart', endTime: '$topThirtyEnd', dataCount: otherTopThirtyBean!.data!.length),
              Row(
                children: [
                  TextButton(
                      onPressed: () {
                        String topThree = otherTopThirtyBean!.data!
                            .getRange(0, otherTopThirtyBean!.data!.length > 30 ? 30 : otherTopThirtyBean!.data!.length)
                            .toList()
                            .asMap()
                            .entries
                            .map((e) => "${(e.key + 1).toString()}\t${e.value.cMCODE}\t${e.value.cMNAME}\t${e.value.cOUNT}")
                            .join("\n");
                        String totalCount = otherTopThirtyBean!.data!
                            .getRange(0, otherTopThirtyBean!.data!.length > 30 ? 30 : otherTopThirtyBean!.data!.length)
                            .fold(0, (value, element) {
                          return value + (element.cOUNT ?? 0);
                        }).toString();

                        "\"其它\" 數據首 三十 大客戶 ${topThirtyStart.substring(5, 7)}/${topThirtyStart.substring(0, 4)}月份累計票數\n"
                                "NO.\t客戶編號\t客戶名稱\t票數\n"
                                "$topThree\n\t\t\t$totalCount"
                            .copyValue();
                      },
                      child: Text("C首三十")),
                  TextButton(
                      onPressed: () {
                        otherTopThirtyBean!.data!
                            .asMap()
                            .entries
                            .map((e) => "${(e.key + 1).toString()}\t${e.value.cMCODE}\t${e.value.cMNAME}\t${e.value.cOUNT}")
                            .join("\n")
                            .copyValue();
                      },
                      child: Text("C全部")),
                ],
              ),
              Container(
                padding: const EdgeInsets.all(10),
                width: MediaQuery.of(context).size.width / 1.5,
                child: Table(
                  border: TableBorder.all(color: Colors.black),
                  children: [
                    tabRows(["NO.", "客戶編號", "客戶名稱", "票數"]),
                    ...otherTopThirtyBean!.data!.asMap().entries.map((entry) {
                      return TableRow(children: [
                        TableCell(
                            child: Text(
                          (entry.key + 1).toString(),
                          style: const TextStyle(color: Colors.blue, fontSize: 12),
                        )),
                        TableCell(child: Text(entry.value.cMCODE.toString(), style: const TextStyle(color: Colors.blue, fontSize: 12))),
                        TableCell(child: Text(entry.value.cMNAME.toString(), style: const TextStyle(color: Colors.blue, fontSize: 12))),
                        TableCell(child: Text(entry.value.cOUNT.toString(), style: const TextStyle(color: Colors.blue, fontSize: 12))),
                      ]);
                    }),
                  ],
                ),
              ),
            ],
          ],
        ),
      ],
    );
  }

  Widget _thirdPartyWidget(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Column(
          children: [
            Row(
              children: [
                IconButton(
                  onPressed: () {
                    if (thirdPartyLoading) return;
                    dailyReportBloc?.add(ThirdPartyDataEvent(startDate: thirdPartyStart, endDate: thirdPartyEnd));
                  },
                  icon: AnimatedSwitcher(
                      duration: Duration(seconds: 1),
                      child: thirdPartyLoading
                          ? SizedBox(key: ValueKey("loading"), width: 40, height: 40, child: CircularProgressIndicator())
                          : const SizedBox(
                              key: ValueKey("search"),
                              height: 40,
                              child: Row(children: [Icon(Icons.search, color: Colors.green), Text("查询第三方", style: TextStyle(color: Colors.green))]))),
                ),
                TextButton(
                    onPressed: () async {
                      if (kIsWeb) {
                        String url = "${Uri.base.toString()}daily_data_entry";
                        debugPrint('无法打开 URL: $url');
                        if (!await launchUrl(
                          Uri.parse(url),
                          mode: LaunchMode.externalApplication,
                        )) {
                          debugPrint('无法打开 URL: $url');
                        }
                      } else {
                        Navigator.push(context, MaterialPageRoute(builder: (_) {
                          return DailyDataEntryPage();
                        }));
                      }
                    },
                    child: Text("C第三方統計")),
              ],
            ),
            CalendarView(
              day: 1,
              onInitDateChanged: (startDateTime, startStr, endDateTime, endStr) {
                thirdPartyStart = "${startStr}";
                thirdPartyEnd = "${endStr}";
              },
              onDateStartChanged: (startDateTime, startStr) {
                thirdPartyStart = "${startStr}";
              },
              onDateEndChanged: (endDateTime, endStr) {
                thirdPartyEnd = "${endStr}";
              },
            ),
          ],
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (thirdPartyBean != null && thirdPartyBean?.status == 1) ...[
              _dateWidget(startTime: '$thirdPartyStart', endTime: '$thirdPartyEnd', dataCount: thirdPartyBean!.data!.length),
              TextButton(
                  onPressed: () {
                    var dsfData = thirdPartyBean!.data!.map((e) {
                      // 判断每个数据是否为0，如果为0则替换为""
                      var hKIPO = e.hKIPO == 0 ? "" : e.hKIPO;
                      var hKPO = e.hKPO == 0 ? "" : e.hKPO;
                      var yZXBG = e.yZXBG == 0 ? "" : e.yZXBG;
                      var sF = e.sF == 0 ? "" : e.sF;
                      var aF = e.aF == 0 ? "" : e.aF;
                      var bYD = e.bYD == 0 ? "" : e.bYD;
                      var pU = e.pU == 0 ? "" : e.pU;
                      var cXC = e.cXC == 0 ? "" : e.cXC;
                      var tCDDC = e.tCDDC == 0 ? "" : e.tCDDC;
                      var tCHVAN = e.tCHVAN == 0 ? "" : e.tCHVAN;
                      var dSDDC = e.dSDDC == 0 ? "" : e.dSDDC;
                      var dSHVAN = e.dSHVAN == 0 ? "" : e.dSHVAN;

                      var skDdc = e.skDdc == 0 ? "" : e.skDdc;
                      var skHvan = e.skHvan == 0 ? "" : e.skHvan;
                      var skBqsjBwb = e.skBqsjBwb == 0 ? "" : e.skBqsjBwb;

                      var tCJ = e.tCJ == 0 ? "" : e.tCJ;
                      var dSJ = e.dSJ == 0 ? "" : e.dSJ;
                      return "${e.cREATEDATE}\t$hKIPO\t$hKPO\t$yZXBG\t$sF\t$aF\t$bYD\t$pU\t$cXC\t$tCDDC\t$tCHVAN\t$dSDDC\t$dSHVAN\t${skDdc}\t${skHvan}\t${skBqsjBwb}\t$tCJ\t$dSJ";
                    }).join("\n");
                    dsfData.copyValue();
                  },
                  child: Text("C第三方")),
              TextButton(
                  onPressed: () {
                    var e = thirdPartyBean!.data!.last;
                    // 判断每个数据是否为0，如果为0则替换为""
                    var hKIPO = e.hKIPO == 0 ? "" : e.hKIPO;
                    var hKPO = e.hKPO == 0 ? "" : e.hKPO;
                    var yZXBG = e.yZXBG == 0 ? "" : e.yZXBG;
                    var sF = e.sF == 0 ? "" : e.sF;
                    var aF = e.aF == 0 ? "" : e.aF;
                    var bYD = e.bYD == 0 ? "" : e.bYD;
                    var pU = e.pU == 0 ? "" : e.pU;
                    var cXC = e.cXC == 0 ? "" : e.cXC;
                    var tCDDC = e.tCDDC == 0 ? "" : e.tCDDC;
                    var tCHVAN = e.tCHVAN == 0 ? "" : e.tCHVAN;
                    var dSDDC = e.dSDDC == 0 ? "" : e.dSDDC;
                    var dSHVAN = e.dSHVAN == 0 ? "" : e.dSHVAN;

                    var skDdc = e.skDdc == 0 ? "" : e.skDdc;
                    var skHvan = e.skHvan == 0 ? "" : e.skHvan;
                    var skBqsjBwb = e.skBqsjBwb == 0 ? "" : e.skBqsjBwb;

                    var tCJ = e.tCJ == 0 ? "" : e.tCJ;
                    var dSJ = e.dSJ == 0 ? "" : e.dSJ;

                    """${e.cREATEDATE}\t$hKIPO\t$hKPO\t$yZXBG\t$sF\t$aF\t$bYD\t$pU\t$cXC\t$tCDDC\t$tCHVAN\t$dSDDC\t$dSHVAN\t${skDdc}\t${skHvan}\t${skBqsjBwb}\t$tCJ\t$dSJ"""
                        .copyValue();
                  },
                  child: Text("C第三方 最后一行")),
              TextButton(
                  onPressed: () {
                    var dsfData = thirdPartyBean!.data!.map((e) {
                      // 判断每个数据是否为0，如果为0则替换为""
                      var hKIPO = e.hKIPO == 0 ? "" : e.hKIPO;
                      var hKPO = e.hKPO == 0 ? "" : e.hKPO;
                      var yZXBG = e.yZXBG == 0 ? "" : e.yZXBG;
                      var sF = e.sF == 0 ? "" : e.sF;
                      var aF = e.aF == 0 ? "" : e.aF;
                      var bYD = e.bYD == 0 ? "" : e.bYD;
                      var pU = e.pU == 0 ? "" : e.pU;
                      var cXC = e.cXC == 0 ? "" : e.cXC;
                      var tCDDC = e.tCDDC == 0 ? "" : e.tCDDC;
                      var tCHVAN = e.tCHVAN == 0 ? "" : e.tCHVAN;
                      var dSDDC = e.dSDDC == 0 ? "" : e.dSDDC;
                      var dSHVAN = e.dSHVAN == 0 ? "" : e.dSHVAN;

                      var skDdc = e.skDdc == 0 ? "" : e.skDdc;
                      var skHvan = e.skHvan == 0 ? "" : e.skHvan;
                      var skBqsjBwb = e.skBqsjBwb == 0 ? "" : e.skBqsjBwb;

                      var tCJ = e.tCJ == 0 ? "" : e.tCJ;
                      var dSJ = e.dSJ == 0 ? "" : e.dSJ;
                      return "${e.cREATEDATE}\t$hKIPO\t$hKPO\t$yZXBG\t$sF\t$aF\t$bYD\t$pU\t$cXC\t$tCDDC\t$tCHVAN\t$dSDDC\t$dSHVAN\t${skDdc}\t${skHvan}\t${skBqsjBwb}\t$tCJ\t$dSJ";
                    }).join("\n");
                    var hKIPOAll = thirdPartyBean!.data!.fold(0, (value, element) => value + (element.hKIPO ?? 0));
                    var hKPOAll = thirdPartyBean!.data!.fold(0, (value, element) => value + (element.hKPO ?? 0));
                    var yZXBGAll = thirdPartyBean!.data!.fold(0, (value, element) => value + (element.yZXBG ?? 0));
                    var sFAll = thirdPartyBean!.data!.fold(0, (value, element) => value + (element.sF ?? 0));
                    var aFAll = thirdPartyBean!.data!.fold(0, (value, element) => value + (element.aF ?? 0));
                    var bYDAll = thirdPartyBean!.data!.fold(0, (value, element) => value + (element.bYD ?? 0));
                    var pUAll = thirdPartyBean!.data!.fold(0, (value, element) => value + (element.pU ?? 0));
                    var cXCAll = thirdPartyBean!.data!.fold(0, (value, element) => value + (element.cXC ?? 0));
                    var tCDDCAll = thirdPartyBean!.data!.fold(0, (value, element) => value + (element.tCDDC ?? 0));
                    var tCHVANAll = thirdPartyBean!.data!.fold(0, (value, element) => value + (element.tCHVAN ?? 0));
                    var dSDDCAll = thirdPartyBean!.data!.fold(0, (value, element) => value + (element.dSDDC ?? 0));
                    var dSHVANAll = thirdPartyBean!.data!.fold(0, (value, element) => value + (element.dSHVAN ?? 0));
                    var skDdcAll = thirdPartyBean!.data!.fold(0, (value, element) => value + (element.skDdc ?? 0));
                    var skHvanAll = thirdPartyBean!.data!.fold(0, (value, element) => value + (element.skHvan ?? 0));
                    var skBqsjBwbAll = thirdPartyBean!.data!.fold(0, (value, element) => value + (element.skBqsjBwb ?? 0));
                    var tCJAll = thirdPartyBean!.data!.fold(0, (value, element) => value + (element.tCJ ?? 0));
                    var dSJAll = thirdPartyBean!.data!.fold(0, (value, element) => value + (element.dSJ ?? 0));
                    "${dsfData}\n\t$hKIPOAll\t$hKPOAll\t$yZXBGAll\t$sFAll\t$aFAll\t$bYDAll\t$pUAll\t$cXCAll\t$tCDDCAll\t$tCHVANAll\t$dSDDCAll\t$dSHVANAll\t$skDdcAll\t$skHvanAll\t$skBqsjBwbAll\t$tCJAll\t$dSJAll"
                        .copyValue();
                  },
                  child: Text("C第三方 All")),
              Table(
                border: TableBorder.all(color: Colors.black),
                children: [
                  tabRows([
                    "日期",
                    "郵政站(櫃檯取件)",
                    "郵政櫃(Locker)",
                    "郵政小包裹",
                    "順豐",
                    "菜烏",
                    "便利店",
                    "CXC 自提點",
                    "CXC自營點",
                    " 電單車 ",
                    "貨VAN",
                    "電單車",
                    "貨VAN",
                    "收客票數》電單車",
                    "收客票數》貨VAN",
                    "收客票數》頂北區司機/兵位包底數",
                    "同城件",
                    "電商件"
                  ]),
                  ...thirdPartyBean!.data!.map((e) => TableRow(children: [
                        TableCell(child: Center(child: Text(e.cREATEDATE.toString()))),
                        TableCell(child: Center(child: Text(e.hKIPO.toString()))),
                        TableCell(child: Center(child: Text(e.hKPO.toString()))),
                        TableCell(child: Center(child: Text(e.yZXBG.toString()))),
                        TableCell(child: Center(child: Text(e.sF.toString()))),
                        TableCell(child: Center(child: Text(e.aF.toString()))),
                        TableCell(child: Center(child: Text(e.bYD.toString()))),
                        TableCell(child: Center(child: Text(e.pU.toString()))),
                        TableCell(child: Center(child: Text(e.cXC.toString()))),
                        TableCell(child: Center(child: Text(e.tCDDC.toString()))),
                        TableCell(child: Center(child: Text(e.tCHVAN.toString()))),
                        TableCell(child: Center(child: Text(e.dSDDC.toString()))),
                        TableCell(child: Center(child: Text(e.dSHVAN.toString()))),
                        // 新增三列
                        TableCell(
                            child: Center(
                                child: Text(
                          e.skDdc.toString(),
                          style: TextStyle(color: Colors.deepPurple),
                        ))),
                        TableCell(
                            child: Center(
                                child: Text(
                          e.skHvan.toString(),
                          style: TextStyle(color: Colors.deepPurple),
                        ))),
                        TableCell(
                            child: Center(
                                child: Text(
                          e.skBqsjBwb.toString(),
                          style: TextStyle(color: Colors.deepPurple),
                        ))),
                        TableCell(child: Center(child: Text(e.tCJ.toString()))),
                        TableCell(child: Center(child: Text(e.dSJ.toString()))),
                      ])),
                  tabRows(["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]),
                  tabRowWidgets([
                    Text("日期 （总数）"),
                    copyWidget(Text("${thirdPartyBean!.data!.fold(0, (value, element) => value + (element.hKIPO ?? 0))}", style: TextStyle(color: Colors.red))),
                    copyWidget(Text("${thirdPartyBean!.data!.fold(0, (value, element) => value + (element.hKPO ?? 0))}", style: TextStyle(color: Colors.red))),
                    copyWidget(Text("${thirdPartyBean!.data!.fold(0, (value, element) => value + (element.yZXBG ?? 0))}", style: TextStyle(color: Colors.red))),
                    copyWidget(Text("${thirdPartyBean!.data!.fold(0, (value, element) => value + (element.sF ?? 0))}", style: TextStyle(color: Colors.red))),
                    copyWidget(Text("${thirdPartyBean!.data!.fold(0, (value, element) => value + (element.aF ?? 0))}", style: TextStyle(color: Colors.red))),
                    copyWidget(Text("${thirdPartyBean!.data!.fold(0, (value, element) => value + (element.bYD ?? 0))}", style: TextStyle(color: Colors.red))),
                    copyWidget(Text("${thirdPartyBean!.data!.fold(0, (value, element) => value + (element.pU ?? 0))}", style: TextStyle(color: Colors.red))),
                    copyWidget(Text("${thirdPartyBean!.data!.fold(0, (value, element) => value + (element.cXC ?? 0))}", style: TextStyle(color: Colors.red))),
                    copyWidget(Text("${thirdPartyBean!.data!.fold(0, (value, element) => value + (element.tCDDC ?? 0))}", style: TextStyle(color: Colors.red))),
                    copyWidget(
                        Text("${thirdPartyBean!.data!.fold(0, (value, element) => value + (element.tCHVAN ?? 0))}", style: TextStyle(color: Colors.red))),
                    copyWidget(Text("${thirdPartyBean!.data!.fold(0, (value, element) => value + (element.dSDDC ?? 0))}", style: TextStyle(color: Colors.red))),
                    copyWidget(
                        Text("${thirdPartyBean!.data!.fold(0, (value, element) => value + (element.dSHVAN ?? 0))}", style: TextStyle(color: Colors.red))),
                    copyWidget(Text("${thirdPartyBean!.data!.fold(0, (value, element) => value + (element.skDdc ?? 0))}",
                        style: TextStyle(color: Colors.deepPurple))), // 新增三列
                    copyWidget(Text("${thirdPartyBean!.data!.fold(0, (value, element) => value + (element.skHvan ?? 0))}",
                        style: TextStyle(color: Colors.deepPurple))), // 新增三列
                    copyWidget(Text("${thirdPartyBean!.data!.fold(0, (value, element) => value + (element.skBqsjBwb ?? 0))}",
                        style: TextStyle(color: Colors.deepPurple))), // 新增三列
                    copyWidget(Text("${thirdPartyBean!.data!.fold(0, (value, element) => value + (element.tCJ ?? 0))}", style: TextStyle(color: Colors.red))),
                    copyWidget(Text("${thirdPartyBean!.data!.fold(0, (value, element) => value + (element.dSJ ?? 0))}", style: TextStyle(color: Colors.red))),
                  ]),
                ],
              ),
            ],
          ],
        ),
      ],
    );
  }
}
